// import { Link, Stack } from 'expo-router';
import BaseEmpty from '@/components/BaseEmpty';
import React, { forwardRef, useImperativeHandle, useState } from 'react';
import { Modal, type ModalBaseProps, StyleSheet, TouchableWithoutFeedback, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import tw from 'twrnc';

interface IProps extends ModalBaseProps {
  position?: 'top' | 'bottom' | 'center';
  children: React.ReactNode
}

export interface ModalInstance {
  toggle: () => void;
}

// 使用方式：父组件通过useRef触发弹框：modalRef.current.toggle()

/**
 * position 弹框布局位置：置顶、底部、居中
 * otherProps 原生Modal属性
 */

const BaseModal = React.memo(forwardRef((props: IProps, ref) => {
  const { position = 'center', children, ...otherProps } = props
  const [modalVisible, setModalVisible] = useState<boolean>(false)
  const positionStyle = {
    top: 'justify-start',
    bottom: 'justify-end',
    center: 'justify-center'
  }

  const toggle = () => {
    setModalVisible(!modalVisible)
  }

  useImperativeHandle(ref, () => {
    return {
      toggle,
    };
  });

  return <View>
    <Modal
      animationType="fade"
      transparent={true}
      visible={modalVisible}
      {...otherProps}
    >
      <TouchableWithoutFeedback onPress={toggle}>
        {/* StyleSheet 里字段被冻结为常量，变为变量就额外在style中写入 */}
        <SafeAreaView style={tw.style(styles.mask, positionStyle[position])}>
          <TouchableWithoutFeedback>
            <View style={tw.style(styles[position], 'p-6', 'bg-white')}>
              {children || <BaseEmpty description="内容为空" />}
            </View>
          </TouchableWithoutFeedback>
        </SafeAreaView>
      </TouchableWithoutFeedback>
    </Modal>
  </View>;
}))

const styles = StyleSheet.create({
  mask: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.3)',
  },
  top: {
    borderBottomLeftRadius: 12,
    borderBottomRightRadius: 12,
  },
  bottom: {
    borderTopLeftRadius: 12,
    borderTopRightRadius: 12,
  },
  center: {
    borderTopLeftRadius: 12,
    borderTopRightRadius: 12,
    borderBottomLeftRadius: 12,
    borderBottomRightRadius: 12,
    marginLeft: 30,
    marginRight: 30
  },
});
 
export default BaseModal;